package com.leezai.mqtt.handler;

import com.alibaba.fastjson2.JSONObject;
import com.leezai.mqtt.Parser.ByteStreamParser;
import com.leezai.mqtt.config.ParserConfig;
import com.leezai.mqtt.config.Properties;
import com.leezai.mqtt.dto.HexDto;
import com.leezai.mqtt.dto.TopicConfig;
import com.leezai.mqtt.utils.TopicMatcher;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class MessageProcessorImpl implements MessageProcessor {

    private final ByteStreamParser byteStreamParser = new ByteStreamParser();
    private final Properties properties;

    // 构造函数
    public MessageProcessorImpl() {
        this.properties = Properties.getInstance();
    }


    public void handleMessage(String realTopic, byte[] payload) {
        //todo 此处处理逻辑第三方需要自行实现，下方默认处理逻辑为参考示例，只有数据解析功能
        String configTopic = matchConfigTopic(realTopic);
        TopicConfig topicConfig = properties.getTopicConfig(configTopic);
        if (topicConfig != null && "hex".equals(topicConfig.getType())) {
            List<HexDto> rulesForTopic = ParserConfig.getRulesForTopic(configTopic);
            if (rulesForTopic != null) {
                JSONObject parsedData = byteStreamParser.parseBytes(payload, rulesForTopic);
                // 处理解析后的数据
//                System.out.println("解析结果: " + parsedData);
            }
        }
    }


    /**
     * 根据实际topic匹配配置中的topic
     *
     * @param actualTopic 实际收到的topic
     * @return 匹配的配置topic
     */
    private String matchConfigTopic(String actualTopic) {
        if (actualTopic == null) {
            return null;
        }
        Set<String> topicSet = properties.getTopics().stream().map(TopicConfig::getTopic).collect(Collectors.toSet());
        // 获取所有配置的topic规则
        if (topicSet.isEmpty()) {
            return null;
        }

        return TopicMatcher.matchTopic(actualTopic, topicSet);
    }

    /**
     * 获取指定topic的解析规则
     *
     * @param topic 实际topic
     * @return 解析规则列表
     */
    private List<HexDto> getRulesForTopic(String topic) {
        String matchedTopic = matchConfigTopic(topic);
        if (matchedTopic != null) {
            return ParserConfig.getRulesForTopic(matchedTopic);
        }
        return null;
    }
}
